﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Stee.CAP8.Communication.HttpInterface
{
    /// <summary>
    /// Extensions methods to set Timeout for <see cref="HttpRequestMessage"/> />.
    /// </summary>
    internal static class HttpRequestExtensions
    {
        private const string TimeoutPropertyKey = "RequestTimeout";
        private const string TokenKey = "Bearer";
        private const string SessionIDKey = "x-sessionid";
        public static void SetTimeout(this HttpRequestMessage request, TimeSpan? timeout)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            request.Properties[TimeoutPropertyKey] = timeout;
        }

        public static TimeSpan? GetTimeout(this HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Properties.TryGetValue(TimeoutPropertyKey, out var value)
                && value is TimeSpan timeout)
            {
                return timeout;
            }

            return null;
        }

        public static void SetToken(this HttpRequestMessage request, string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue(TokenKey, token);
            }
        }

        public static void SetSessionID(this HttpRequestMessage request, string sessionID)
        {
            if (!string.IsNullOrEmpty(sessionID))
            {
                request.Headers.Add(SessionIDKey, sessionID);
            }
        }
    }
}
